package jdbc;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

public class JDBCExample {

	public static void main(String[] args) {
		// String driver="oracle.jdbc.driver.OracleDriver";
		// String url="jdbc:oracle:thin:@192.168.1.2:1521:ora92";
		// String username="scott";
		// String password="tiger";
		String driver = "com.mysql.jdbc.Driver";
		String url = "jdbc:mysql://localhost/test_java";
		String username = "dong";
		String password = "xiaodong";
		String sql = "insert into jdbc01_users(username,password) values(?,?)";// 写入DB
		String sql1 = "select * from jdbc01_users";// 读取
		try {
			Class.forName(driver);
			// new oracle.jdbc.driver.OracleDriver();和11行代码效果相同
			Connection conn = DriverManager.getConnection(url, username, password);
			// Statement stat=conn.createStatement();
			PreparedStatement pstmt = conn.prepareStatement(sql);
			pstmt.setString(1, "aaa");
			pstmt.setString(2, "bbb");
			pstmt.executeUpdate();
			PreparedStatement pstmt1 = conn.prepareStatement(sql1);
			ResultSet rs = pstmt1.executeQuery();
			while (rs.next()) {
				System.out.println("name:" + rs.getString("username") + "\npassword:" + rs.getString("password"));
			}
			pstmt.close();
			rs.close();
			pstmt1.close();
			conn.close();
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}

}
